package com.cheng.im.service.util;

import com.alibaba.fastjson2.JSONObject;
import com.cheng.im.common.constants.RedisConstants;
import com.cheng.im.common.entity.SessionCache;
import com.cheng.im.common.entity.UserCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UserSessionUtils {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public Map<String, SessionCache> getUserSession(String appId, String userId){
        String key = appId + RedisConstants.UserSessionConstants + userId;

        HashOperations<String, String, String> sessionTemplate = stringRedisTemplate.opsForHash();
        Map<String, String> entries = sessionTemplate.entries(key);

        Map<String, SessionCache> sessionCacheMap = new HashMap<>();
        for (Map.Entry<String, String> entry : entries.entrySet()) {
            sessionCacheMap.put(entry.getKey(), JSONObject.parseObject(entry.getValue(), SessionCache.class));
        }

        return sessionCacheMap;
    }

    public SessionCache getUserSession(String appId, String userId, String sessionId){

        String key = appId + RedisConstants.UserSessionConstants + userId;

        HashOperations<String, String, String> sessionTemplate = stringRedisTemplate.opsForHash();
        String sessionCacheString = sessionTemplate.get(key, sessionId);

        if (StringUtils.isEmpty(sessionCacheString)) {
            return null;
        }

        SessionCache sessionCache = JSONObject.parseObject(sessionCacheString, SessionCache.class);

        return sessionCache;
    }
}
